package com.ziyun.erp.modules.goodsCategory.service.impl;

import com.sun.org.apache.xpath.internal.operations.Bool;
import com.utility.New;
import com.ziyun.erp.common.e.goods.GoodsTypeEnum;
import com.ziyun.erp.common.utils.JsonUtils;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.goods.entity.GoodsAttributeEntity;
import com.ziyun.erp.modules.goods.entity.GoodsTemplateEntity;
import com.ziyun.erp.modules.goods.service.GoodsService;
import com.ziyun.erp.modules.goods.service.GoodsTemplateService;
import com.ziyun.erp.modules.goods.service.impl.GoodsServiceImpl;
import com.ziyun.erp.modules.goodsCategory.entity.GoodsCategoryRelationEntity;
import com.ziyun.erp.modules.goodsCategory.entity.GoodsCategoryVO;
import com.ziyun.erp.modules.goodsCategory.service.GoodsCategoryRelationService;
import com.ziyun.erp.modules.goodsImage.dao.GoodsImageDao;
import com.ziyun.erp.modules.goodsImage.entity.GoodsImageEntity;
import com.ziyun.erp.modules.goodsImage.service.GoodsImageService;
import com.ziyun.erp.modules.quoteParts.entity.QuotePartsEntity;
import com.ziyun.erp.modules.quoteParts.service.QuotePartsService;
import com.ziyun.erp.modules.quoteProductAttributeOptionRelation.entity.QuoteProductAttributeOptionRelationEntity;
import com.ziyun.erp.modules.quoteProductAttributeOptionRelation.service.QuoteProductAttributeOptionRelationService;
import com.ziyun.erp.modules.unitLibrary.entity.UnitLibraryEntity;
import com.ziyun.erp.modules.unitLibrary.service.UnitLibraryService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import com.ziyun.erp.modules.goodsCategory.dao.GoodsCategoryDao;
import com.ziyun.erp.modules.goodsCategory.entity.GoodsCategoryEntity;
import com.ziyun.erp.modules.goodsCategory.service.GoodsCategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("goodsCategoryService")
public class GoodsCategoryServiceImpl extends ServiceImpl<GoodsCategoryDao, GoodsCategoryEntity> implements GoodsCategoryService {

    @Autowired
    private GoodsCategoryDao goodsCategoryDao;
    @Autowired
    private GoodsCategoryRelationService goodsCategoryRelationService;
    @Autowired
    private GoodsImageService goodsImageService;
    @Autowired
    private GoodsTemplateService goodsTemplateService;
    @Autowired
    private QuotePartsService quotePartsService;
    @Autowired
    private QuoteProductAttributeOptionRelationService quoteProductAttributeOptionRelationService;
    @Autowired
    private UnitLibraryService unitLibraryService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsImageDao goodsImageDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<GoodsCategoryEntity> page = this.selectPage(
                new Query<GoodsCategoryEntity>(params).getPage(),
                new EntityWrapper<GoodsCategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<GoodsCategoryEntity> queryAllList() {
        return this.selectList(new EntityWrapper<GoodsCategoryEntity>()
                .eq("`disabled`", 0).orderBy("category_id", true));
    }

    @Override
    //根据分类id获得分类全对象
    public R getCatNamesByCategoryId(Integer categoryId) {
        List<GoodsCategoryEntity> goodsCategoryList = goodsCategoryDao.getCatNamesByCategoryId(categoryId);
                StringBuffer categoryNames = new StringBuffer();
        for (GoodsCategoryEntity goodsCategoryEntity:goodsCategoryList) {
            categoryNames.append(goodsCategoryEntity.getCategoryName());
            categoryNames.append("->");
        }
        GoodsCategoryEntity categoryEntity = this.selectById(categoryId);
        categoryNames.append(categoryEntity.getCategoryName());
        //取单位库数据
        Map<String, Object> map = New.hashMap();
        map.put("del_flag",0);
        List<UnitLibraryEntity> unitLibraryList = unitLibraryService.selectByMap(map);
        //根据分类id获得商品模板对象
        GoodsTemplateEntity goodTemplate = goodsTemplateService.getTemplateByCatId(categoryId);
        if(goodTemplate != null){
            //判断模板对象是否含有工艺选项
            String attributeTypes = goodsTemplateService.getAttributeTypes(goodTemplate.getTemplateId());
            if(attributeTypes.contains("craft")){
                goodTemplate.setIncludCraft(true);
            }else{
                goodTemplate.setIncludCraft(false);
            }
            return R.ok().put("categoryNames", categoryNames.toString()).put("goodTemplate",goodTemplate).put("categoryEntity",categoryEntity).put("unitLibraryList",unitLibraryList);
        }else{
            return R.ok().put("categoryNames", categoryNames.toString()).put("categoryEntity",categoryEntity).put("unitLibraryList",unitLibraryList);
        }

    }

    @Override
    //根据模板id获得分类对象
    public GoodsCategoryEntity getCatByTemplateId(Long templateId) {
        GoodsCategoryEntity goodsCategoryEntity = goodsCategoryDao.getCatByTemplateId(templateId);
        return goodsCategoryEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGoodsCategoryAndCategoryRelationById(GoodsCategoryVO goodsCategoryVO) {
        GoodsCategoryEntity goodsCategory = new GoodsCategoryEntity();
        if (StringUtils.isNotBlank(goodsCategoryVO.getImgUrl())) {
            goodsCategoryVO.setImgUrl(goodsCategoryVO.getImgUrl().substring(1,goodsCategoryVO.getImgUrl().length()-1).replaceAll("\"",""));
        }
        GoodsCategoryRelationEntity goodsCategoryRelation = new GoodsCategoryRelationEntity();
        BeanUtils.copyProperties(goodsCategoryVO, goodsCategory);
        BeanUtils.copyProperties(goodsCategoryVO, goodsCategoryRelation);
        this.baseMapper.updateById(goodsCategory);
        goodsCategoryRelationService.updateByGoodsCategoryId(goodsCategoryRelation);
        //前端传来的imgUrl不为空时进行图片表的操作
        if (StringUtils.isNotBlank(goodsCategoryVO.getImgUrl())) {
            //修改图片表的imgUrl,先查询有没有,这个属性是后来增加的
            GoodsImageEntity goodsImage = goodsImageService.selectOne(new EntityWrapper<GoodsImageEntity>()
                    .eq("relation_id", goodsCategoryVO.getCategoryId().longValue()).eq("type", 2).eq("disable", 0));
            if (goodsImage != null) {
                //不为空就修改
                goodsImage.setImageUrl(goodsCategoryVO.getImgUrl());
                goodsImageService.update(goodsImage, new EntityWrapper<GoodsImageEntity>().eq("relation_id", goodsCategoryVO.getCategoryId().longValue())
                        .eq("type", 2));
            } else {
                //为空就新增
                goodsImage = insertGoodsImag(goodsCategoryVO.getImgUrl(), goodsCategory.getCategoryId().longValue());
                //将goods_image表id更新到商品分类表中
            goodsCategory.setImgId(goodsImage.getId().toString());
                this.baseMapper.updateById(goodsCategory);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertGoodsCategoryAndCategoryRelation(GoodsCategoryEntity goodsCategory) {
        //设置分类路径,分类级别,是否叶节点
        if (goodsCategory.getParentCategoryId() == 0) {
            //一级分类
            goodsCategory.setCategoryPath(",");
            goodsCategory.setCategoryLevel(1);
            goodsCategory.setWhetherLeaf(false);
        } else {
            GoodsCategoryEntity goodsCategoryEntity = this.baseMapper.selectById(goodsCategory.getParentCategoryId());
            if (goodsCategoryEntity.getParentCategoryId() == 0) {
                //二级分类
                String categoryPath = "," + goodsCategory.getParentCategoryId() + ",";
                goodsCategory.setCategoryPath(categoryPath);
                goodsCategory.setCategoryLevel(2);
                goodsCategory.setWhetherLeaf(false);
            } else {
                //三级分类
                String categoryPath = "," + goodsCategoryEntity.getParentCategoryId() + "," + goodsCategory.getParentCategoryId() + ",";
                goodsCategory.setCategoryPath(categoryPath);
                goodsCategory.setCategoryLevel(3);
                goodsCategory.setWhetherLeaf(true);
            }
        }
        this.baseMapper.insert(goodsCategory);
        GoodsCategoryRelationEntity goodsCategoryRelation = goodsCategory.getGoodsCategoryRelation();
        goodsCategoryRelation.setCategoryId(goodsCategory.getCategoryId());
        goodsCategoryRelationService.insert(goodsCategoryRelation);
        goodsImageService.updateImage(goodsCategory.getCategoryId(),goodsCategory.getImgId());
//        if (StringUtils.isBlank(goodsCategory.getImgUrl())) {
//            //用户未上传图片,则不用操作goods_image表
//            this.baseMapper.updateById(goodsCategory);
//        } else {
//            goodsCategory.setImgUrl(goodsCategory.getImgUrl().substring(1,goodsCategory.getImgUrl().length()-1).replaceAll("\"",""));
//            GoodsImageEntity goodsImage = insertGoodsImag(goodsCategory.getImgUrl(), goodsCategory.getCategoryId().longValue());
//            //将goods_image表id更新到商品分类表中
//            goodsCategory.setImgId(goodsImage.getId().toString());
//            this.baseMapper.updateById(goodsCategory);
//        }
    }

    /**
     * 新建模板后绑定更新分类绑定的模板
     *
     * @param templateId
     * @param categoryId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTemplateId(Long templateId, Integer categoryId) {
        if(categoryId != null){
            goodsCategoryDao.updateTemplateId(templateId, categoryId);
        }

    }

    @Override
    public R info(Integer categoryId) {
        //查询商品分类表
        GoodsCategoryEntity goodsCategory = this.baseMapper.selectById(categoryId);
        //按category_id查询分类关联热门商品表
        GoodsCategoryRelationEntity goodsCategoryRelation = goodsCategoryRelationService.getByCategoryId(categoryId);
        //查询分类图片
        GoodsImageEntity goodsImageEntity = goodsImageService.selectById(goodsCategory.getImgId());
        return R.ok().put("goodsCategory", goodsCategory).put("goodsCategoryRelation", goodsCategoryRelation).put("goodsImageEntity",goodsImageEntity);
    }

    @Override
    public R getGoodsType() {
        // 获取商品类型枚举类
        Map<String, List> mapEnum = new HashMap<>();
        return R.ok().put("goodsTypeEnum", JsonUtils.enumToList(GoodsTypeEnum.class));
    }

    /**
     * 树结构查询
     * @return
     */
    @Override
    public List<GoodsCategoryEntity> select() {
        List<GoodsCategoryEntity> goodsCategoryEntityList = queryAllList();
//        添加顶级菜单
        GoodsCategoryEntity goodsCategoryEntity = new GoodsCategoryEntity();
        goodsCategoryEntity.setCategoryId(0);
        goodsCategoryEntity.setCategoryName("通用分类");
        goodsCategoryEntity.setParentCategoryId(-1);
        goodsCategoryEntity.setOpen(true);
        goodsCategoryEntityList.add(goodsCategoryEntity);
        return goodsCategoryEntityList;
    }

    /**
     * 标记删除分类
     * @param categoryId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void flagDel(Integer categoryId) {
        goodsCategoryDao.flagDel(categoryId);
    }

    /**
     * 更新父子表数据
     * @param goodsCategory
     */
    @Override
    public void updateGodosCategory(GoodsCategoryEntity goodsCategory) {
        //更新分类表数据
        goodsCategoryDao.updateAllColumnById(goodsCategory);
        //更新子表数据
        goodsCategoryRelationService.updateAllColumnById(goodsCategory.getGoodsCategoryRelation());
        //删除需要删除的图片
        String delImage = goodsCategory.getDelImage();
        List<Integer> list = changeStr2List(delImage);
        if (list != null && list.size() > 0) {
            goodsImageDao.fagDelImageByIds(list);
        }
//        goodsImageService.flagDelImage(delImage);
    }


    //抽取新增图片方法
    private GoodsImageEntity insertGoodsImag(String imgUrl, Long relationId) {
        GoodsImageEntity goodsImage = new GoodsImageEntity();
        goodsImage.setImageUrl(imgUrl);
        goodsImage.setRelationId(relationId);
        goodsImage.setType(2);
        goodsImage.setDisable(false);
        goodsImage.setCreateTime(new Date());
        SysUserEntity curentUser = UserUtils.getCurentUser();
        goodsImage.setCreateName(curentUser.getUsername());
        goodsImageService.insert(goodsImage);
        return goodsImage;
    }

    /**
     * 获取 添加商品模板所需信息
     *
     * @return
     */
    @Override
    public Map<String, Object> getAddInfo() {
        Map<String, Object> rsMap = new HashMap<String, Object>();
        // 先获取商品分类
        List<GoodsCategoryEntity> categoryEntityList = this.selectList(new EntityWrapper<GoodsCategoryEntity>()
        .ne("category_id",0)
        .eq("disabled",0));
        // in("goods_type",new ArrayList<String>(Arrays.asList("quote", "fast", "material"))));
        List<Map> categoryTree = categoryTreeHandle(categoryEntityList, 0);
        rsMap.put("categoryTree", categoryTree);
        return rsMap;
    }

    /**
     * 小b发布报价商品算价
     * @param paramBodyMap
     */
    @Override
    public Map<String, Object> countPrice(Map paramBodyMap) {
        Map params = (Map) paramBodyMap.get("params");
        String ids = (String) params.get("ids");
        Integer partsId = (Integer) params.get("partsId");
        Integer categoryId = (Integer) params.get("categoryId");
        Map<String, Object> resultMap = New.hashMap();
        //先获得报价处理器
        GoodsCategoryEntity categoryEntity = null;
        //查特规表
        List<QuoteProductAttributeOptionRelationEntity> quoteProductAttributeOptionRelationEntities = null;
        Boolean flag = true;
        if(categoryId != null){
            //如果分类id不为空,则证明是单部件的,应按照分类id去查
            categoryEntity = this.baseMapper.selectById(categoryId);
            Map<String, Object> map = New.hashMap();
            map.put("category_id",categoryId);
            quoteProductAttributeOptionRelationEntities = quoteProductAttributeOptionRelationService.selectByMap(map);
        }else{
            //如果分类id为空,则正常此次穿过来的是部件id,应按照部件id查询分类id,再查询分类报价处理器类型
            //在此处写一个方法,更具部件id返回分类id
            QuotePartsEntity quotePartsEntity = quotePartsService.selectById(partsId);
            //如果不展示,则不添加
            if(!quotePartsEntity.getDisplay()){
                flag = false;
            }
            categoryEntity = this.baseMapper.selectById(quotePartsEntity.getCategoryId());
            Map<String, Object> map = New.hashMap();
            map.put("category_id",categoryEntity.getCategoryId());
            map.put("parts_id",partsId);
            quoteProductAttributeOptionRelationEntities = quoteProductAttributeOptionRelationService.selectList(
                    new EntityWrapper<QuoteProductAttributeOptionRelationEntity>()
                            .eq("category_id", categoryEntity.getCategoryId())
                            .eq("parts_id", partsId)
                            .isNotNull("attribute_id")
            );
//            quoteProductAttributeOptionRelationEntities = quoteProductAttributeOptionRelationService.selectByMap(map);
        }
        //再根据ids查询map返回对象
        List<Map<String, Object>> attributeValueKeyByOptionIds = this.baseMapper.getAttributeValueKeyByOptionIds(ids);
        resultMap.put("categoryType",categoryEntity.getCategoryHandleType());

        List<Map<String,Object>> list = new ArrayList<>();
        for(int i = 0;i<attributeValueKeyByOptionIds.size();i++){
            Map<String, Object> map = New.hashMap();
            if("craft".equals(String.valueOf(attributeValueKeyByOptionIds.get(i).get("attributeType")))){
                //如果是工艺
                if(quoteProductAttributeOptionRelationEntities != null && quoteProductAttributeOptionRelationEntities.size() > 0){
                    for(int ii = 0;ii<quoteProductAttributeOptionRelationEntities.size();ii++){
                        if(quoteProductAttributeOptionRelationEntities.get(ii).getAttributeId().intValue() == Integer.parseInt(String.valueOf(attributeValueKeyByOptionIds.get(i).get("attributeId")))){
                            if(quoteProductAttributeOptionRelationEntities.get(ii).getAttributeMustChoice() == 1){
                                map.put("optionId",attributeValueKeyByOptionIds.get(i).get("optionId"));
                                map.put("attributeTypeValue",attributeValueKeyByOptionIds.get(i).get("attributeTypeValue"));
                                list.add(map);
                            }
                        }
                    }
                }
            }else{
                //是规格直接添加
                map.put("optionId",attributeValueKeyByOptionIds.get(i).get("optionId"));
                map.put("attributeTypeValue",attributeValueKeyByOptionIds.get(i).get("attributeTypeValue"));
                list.add(map);
            }
        }
        Map<String, Object> map1 = New.hashMap();
        if(categoryId != null){
            map1.put("categoryId",categoryId);
        }else{
            map1.put("categoryId",partsId);
        }
        map1.put("list",list);
        resultMap.put("attributesMap",map1);
        resultMap.put("flag",flag);
        return resultMap;
    }

    /**
     * 根据父级分类id获得categoryIds
     * @param parentCategoryIds
     * @return
     */
    @Override
    public List<Integer> getCategoryIdsByParentIds(List<Integer> parentCategoryIds) {
        return this.baseMapper.getCategoryIdsByParentIds(StringUtils.join(parentCategoryIds, ","));
    }

    @Override
    public GoodsCategoryEntity selectAllGoodsCategory(Integer categoryId) {
        GoodsCategoryEntity categoryEntity = this.baseMapper.selectById(categoryId);
        Map<String, Object> map = New.hashMap();
        map.put("category_id",categoryId);
        map.put("disabled",0);
        List<GoodsCategoryRelationEntity> goodsCategoryRelationEntities = goodsCategoryRelationService.selectByMap(map);
        if(goodsCategoryRelationEntities != null && goodsCategoryRelationEntities.size() == 1){
            categoryEntity.setGoodsCategoryRelation(goodsCategoryRelationEntities.get(0));
        }else{
            throw new RRException("分类id:"+ categoryId +"没有关联分类,错误");
        }
        return categoryEntity;
    }

    @Override
    public void hide(Integer requestParamInteger,Boolean hide) {
        this.baseMapper.hide(requestParamInteger,hide);
    }

    @Override
    public void handHide(Integer categoryId, Boolean hide) {
        //1隐藏,0展示
        //按分类id展示或者屏蔽商品
        goodsService.handHide(categoryId, hide);

    }

    private List<Map> categoryTreeHandle(List<GoodsCategoryEntity> categoryEntityList, int pid) {
        List<Map> resultList = new ArrayList<>();

        //获取顶级元素集合
        Integer parentId;
        for (GoodsCategoryEntity goodsCategory : categoryEntityList) {
            parentId = goodsCategory.getParentCategoryId();
            if (parentId == null || pid == parentId) {
                Map map = new HashMap();
                map.put("label", goodsCategory.getCategoryName());
                map.put("value", goodsCategory.getCategoryId());
                resultList.add(map);
            }
        }

        //获取每个顶层元素的子数据集合
        for (Map map : resultList) {
            int value = Integer.parseInt(map.get("value").toString());
            List<Map> temp = categoryTreeHandle(categoryEntityList, value);
            if (temp.size() > 0) {
                map.put("children", temp);
            }
        }
        return resultList;
    }

    /**
     *字符串转为Integer数组
     */
    private List<Integer> changeStr2List(String str){
        if(org.apache.commons.lang.StringUtils.isNotBlank(str)){
            String[] split = str.split(",");
            List<Integer> ids = New.arrayList();
            for(int j = 0;j<split.length;j++){
                if(org.apache.commons.lang.StringUtils.isNotBlank(split[j])){
                    ids.add(Integer.valueOf(split[j]));
                }
            }
            return ids;
        }else{
            return null;
        }
    }

}
